package starter

import (
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/bean"
	"gitee.com/kristas/booting-go/framework/core/log"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"gitee.com/kristas/booting-go/framework/web"
	"gitee.com/kristas/booting-go/framework/web/controller"
)

func init() {
	framework.Component(new(restApiStarter))
}

type restApiStarter struct {
	types.Component `name:"web:rest_api_starter"`
	Container       web.Server       `wire:""`
	Controllers     []web.Controller `wire:""`
	Log             log.Logger       `wire:""`
}

func (r *restApiStarter) BeanStart() {
	for _, ctr := range r.Controllers {
		endpoints := controller.NewEndpoint(ctr)
		for i := range endpoints {
			r.Container.RegisterEndpoint(endpoints[i])
			r.Log.Debug("add api: %s %s", endpoints[i].GetApiInfo().GetHttpMethod(),
				endpoints[i].GetApiInfo().GetURL())
		}
	}
}

type RestApiProcessor struct {
	Container web.Server `wire:""`
	Log       log.Logger `wire:""`
}

func (r *RestApiProcessor) Order() int {
	return 256
}

func (r *RestApiProcessor) Async() bool {
	return false
}

func (r *RestApiProcessor) Filter(bean bean.Bean) bool {
	_, ok := bean.(web.Controller)
	return ok
}

func (r *RestApiProcessor) Do(bean bean.Bean) error {
	ctr := bean.(web.Controller)
	endpoints := controller.NewEndpoint(ctr)
	for i := range endpoints {
		r.Container.RegisterEndpoint(endpoints[i])
		r.Log.Debug("add api: %s %s", endpoints[i].GetApiInfo().GetHttpMethod(),
			endpoints[i].GetApiInfo().GetURL())
	}
	return nil
}
